<!-- 图表 》 饼状图 -->

<template>
  <EasyChart :baseOption="OPTION" :option="option" :onClick="toClick" />
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import mixChart from '../mixChart'

const name = 'ChartPie'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name,

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [mixChart],

  /**
   * 属性注册
   */
  props: CORE.WEB[name],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 基础配置
     */
    OPTION() {
      const { noTip, topLegend, bottomLegend, init } = this

      const tooltip = noTip ? { show: false } : {}

      let title = { top: '50%', left: '40%' }
      let legend = { top: 'center', right: 10, orient: 'vertical' }
      const serie = CORE.merge({}, init.series[0])

      if (topLegend) {
        title = { top: '55%', left: '50%' }
        legend = { left: 'center', top: 5 }
        CORE.merge(serie, { radius: ['50%', '70%'], center: ['50%', '55%'] })
      } else if (bottomLegend) {
        title = { top: '45%', left: '50%' }
        legend = { left: 'center', bottom: 5 }
        serie.center = ['50%', '40%']
        CORE.merge(serie, { radius: ['50%', '70%'], center: ['50%', '45%'] })
      }

      return CORE.merge({}, init, { tooltip, title, legend, series: [serie] })
    },

    /**
     * 图表配置
     */
    option() {
      const { xData, dataList, title, hasNum, and, unit, serie, diy } = this

      const total = dataList.reduce((num, item) => num + item, 0)
      const data = xData.map((name, i) => ({ name, value: dataList[i] }))
      const formatter = (name) => {
        const index = xData.indexOf(name)
        const value = dataList[index] || 0
        return `${name}${and}${value}${unit}`
      }

      const option = {
        title: {
          text: total,
          subtext: title,
        },
        legend: hasNum ? { formatter } : {},
        series: [
          { ...serie, data },
        ],
      }

      return CORE.merge(option, diy)
    },
  },
}
</script>
